import { defineStore } from "pinia"
export const useCartStore = defineStore('cart',{
    state:()=>{return {goodsList:[]}},
    actions:{
        buy(goods){

            const find  = this.goodsList.find(item => item.id == goods.id)
            if(!find){ 
                if(!goods.num) goods.num = 0
                goods.num++
                this.goodsList = [...this.goodsList,goods]
            }else{
                find.num++
            }
        },
        minus(goods){
            const find  = this.goodsList.find(item => item.id == goods.id)
            if(find){
                find.num--
            }
            const index  = this.goodsList.findIndex(item => item.id == goods.id)
            if(index >= 0&&goods.num==0){
                this.goodsList.splice(index,1)
            }
        },
        clear(){
            this.goodsList.forEach(item => {
                item.num = 0
            })
            this.goodsList=[]
        }
    }
});